﻿using EnvDTE;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using System;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using Task = System.Threading.Tasks.Task;

namespace MysoftVSPlugin
{
    /// <summary>
    /// This is the class that implements the package exposed by this assembly.
    /// </summary>
    /// <remarks>
    /// <para>
    /// The minimum requirement for a class to be considered a valid package for Visual Studio
    /// is to implement the IVsPackage interface and register itself with the shell.
    /// This package uses the helper classes defined inside the Managed Package Framework (MPF)
    /// to do it: it derives from the Package class that provides the implementation of the
    /// IVsPackage interface and uses the registration attributes defined in the framework to
    /// register itself and its components with the shell. These attributes tell the pkgdef creation
    /// utility what data to put into .pkgdef file.
    /// </para>
    /// <para>
    /// To get loaded into VS, the package must be referred by &lt;Asset Type="Microsoft.VisualStudio.VsPackage" ...&gt; in .vsixmanifest file.
    /// </para>
    /// </remarks>
    [PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)]
    [Guid(GuidList.guidCodeSearchPkgString)]
    [ProvideMenuResource("Menus.ctmenu", 1)]
    public sealed class MysoftVSPluginPackage : AsyncPackage
    {
        #region Package Members

        /// <summary>
        /// Initialization of the package; this method is called right after the package is sited, so this is the place
        /// where you can put all the initialization code that rely on services provided by VisualStudio.
        /// </summary>
        /// <param name="cancellationToken">A cancellation token to monitor for initialization cancellation, which can occur when VS is shutting down.</param>
        /// <param name="progress">A provider for progress updates.</param>
        /// <returns>A task representing the async work of package initialization, or an already completed task if there is none. Do not return null from this method.</returns>
        protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress)
        {
            await this.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
            await Command1.InitializeAsync(this);
            Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", this.ToString()));
            base.Initialize();

            // Add our command handlers for menu (commands must exist in the .vsct file)
            OleMenuCommandService mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService;
            if (null != mcs)
            {
                // Create the command for the menu item.
                CommandID menuCommandID = new CommandID(GuidList.guidCodeSearchCmdSet, (int)PkgCmdIDList.cmdidMyCommand);
                OleMenuCommand menuItem = new OleMenuCommand(MenuItemCallback, menuCommandID);
                menuItem.BeforeQueryStatus += menuItem_BeforeQueryStatus;


                mcs.AddCommand(menuItem);


                CommandID cmdID2 = new CommandID(GuidList.guidComponentSearch2CmdSet, (int)PkgCmdIDList.cmdidMyCommand2);
                OleMenuCommand menuCmd2 = new OleMenuCommand(MenuItemCallback_Component, cmdID2);
                mcs.AddCommand(menuCmd2);

                CommandID cmdID3 = new CommandID(GuidList.guidComponentSearch3CmdSet, (int)PkgCmdIDList.cmdidMyCommand3);
                OleMenuCommand menuCmd3 = new OleMenuCommand(MenuItemCallback_Component, cmdID3);
                mcs.AddCommand(menuCmd3);
            }



            // When initialized asynchronously, the current thread may be a background thread at this point.
            // Do any initialization that requires the UI thread after switching to the UI thread.

        }
        /// <summary>
        /// 根据某种条件显示搜索代码的按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuItem_BeforeQueryStatus(object sender, EventArgs e)
        {
            OleMenuCommand cmd = sender as OleMenuCommand;
            if (cmd != null)
            {
                IntPtr hierarchyPtr, selectionContainerPtr;
                uint projectItemId;
                IVsMultiItemSelect mis;
                IVsMonitorSelection monitorSelection = (IVsMonitorSelection)Package.GetGlobalService(typeof(SVsShellMonitorSelection));
                monitorSelection.GetCurrentSelection(out hierarchyPtr, out projectItemId, out mis, out selectionContainerPtr);

                IVsHierarchy hierarchy = Marshal.GetTypedObjectForIUnknown(hierarchyPtr, typeof(IVsHierarchy)) as IVsHierarchy;
                if (hierarchy != null)
                {
                    object value;
                    hierarchy.GetProperty(projectItemId, (int)__VSHPROPID.VSHPROPID_Name, out value);
                    if (value != null && (value.ToString().EndsWith(".cs", StringComparison.OrdinalIgnoreCase)
                        || value.ToString().EndsWith(".aspx", StringComparison.OrdinalIgnoreCase)
                        || value.ToString().EndsWith(".js", StringComparison.OrdinalIgnoreCase)
                        || value.ToString().EndsWith(".vb", StringComparison.OrdinalIgnoreCase)
                        ))
                    {
                        cmd.Visible = true;
                    }
                    else
                    {
                        cmd.Visible = false;
                    }
                }

            }
        }


        /// <summary>
        /// This function is the callback used to execute a command when the a menu item is clicked.
        /// See the Initialize method to see how the menu item is associated to this function using
        /// the OleMenuCommandService service and the MenuCommand class.
        /// </summary>
        private void MenuItemCallback(object sender, EventArgs e)
        {
            DTE dte = ServiceProvider.GlobalProvider.GetService(typeof(DTE)) as DTE;
            if (dte == null) return;


            CodeMainWindow window = new CodeMainWindow(ref dte);
            window.Show();

            // Show a Message Box to prove we were here
            //IVsUIShell uiShell = (IVsUIShell)GetService(typeof(SVsUIShell));
            //uiShell.c

            //Guid clsid = Guid.Empty;
            //int result;

            //Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(uiShell.ShowMessageBox(
            //           0,
            //           ref clsid,
            //           "CodeSearch",
            //           string.Format(CultureInfo.CurrentCulture, "Inside {0}.MenuItemCallback()", this.ToString()),
            //           string.Empty,
            //           0,
            //           OLEMSGBUTTON.OLEMSGBUTTON_OK,
            //           OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST,
            //           OLEMSGICON.OLEMSGICON_INFO,
            //           0,        // false
            //           out result));
        }
        private void MenuItemCallback_Component(object sender, EventArgs e)
        {
            DTE dte = ServiceProvider.GlobalProvider.GetService(typeof(DTE)) as DTE;
            if (dte == null) return;
            //DTE2 dte2 = ServiceProvider.GlobalProvider.GetService(typeof(DTE2)) as DTE2;
            SelectedItems SelItems = dte.SelectedItems;
            if (SelItems.Item(1).ProjectItem == null)
            {
                string selPath = SelItems.Item(1).Project.FileName.Substring(0, SelItems.Item(1).Project.FileName.LastIndexOf("\\"));
                string projectFilePath = string.Format("{0}\\{1}", selPath, "1.txt");
                if (!File.Exists(projectFilePath))
                {
                    File.Create(projectFilePath).Close();
                }
                SelItems.Item(1).Project.ProjectItems.AddFromFile(projectFilePath);
            }
            else
            {
                string selPath = SelItems.Item(1).ProjectItem.get_FileNames(0);
                string projectFilePath = string.Format("{0}\\{1}", selPath, "1.txt");
                if (!File.Exists(projectFilePath))
                {
                    File.Create(projectFilePath).Close();
                }
                SelItems.Item(1).ProjectItem.ProjectItems.AddFromFile(projectFilePath);
            }
        }
        #endregion
    }
}
